<template>
  <view class="detail-page">
    <!-- 顶部红包图片 -->
    <view class="reward-banner">
      <image :src="BASE_URL + (taskInfo.omsGoodsInfo?.headerImg || taskInfo.baseShopItem?.headerImg)" mode="aspectFill" class="banner-img" />
    </view>

    <!-- 任务内容区域 -->
    <view class="task-content">
      <!-- 任务标题 -->
      <view class="task-header"> {{ taskInfo.taskName }} </view>

      <!-- 商品信息 -->
      <view class="info-section" v-if="taskInfo.buyType === '01'">
        <view class="info-item">
          <view class="label">成分</view>
          <view class="divider"></view>
          <view class="value">{{ taskInfo.omsGoodsInfo?.ingredients }}</view>
        </view>
        <view class="info-item">
          <view class="label">效果</view>
          <view class="divider"></view>
          <view class="value">{{ taskInfo.omsGoodsInfo?.effect }}</view>
        </view>
        <view class="info-item">
          <view class="label">适用人群</view>
          <view class="divider"></view>
          <view class="value">{{ taskInfo.omsGoodsInfo?.suitable }}</view>
        </view>
        <view class="info-item">
          <view class="label">使用方法</view>
          <view class="divider"></view>
          <view class="value">{{ taskInfo.omsGoodsInfo?.usageMethod }}</view>
        </view>
      </view>

      <!-- 项目信息 -->
      <view class="info-section" v-if="taskInfo.buyType === '02'">
        <view class="info-item">
          <view class="label">主要功能</view>
          <view class="value">{{ taskInfo.baseShopItem?.features }}</view>
        </view>
        <view class="info-item">
          <view class="label">使用方法</view>
          <view class="value">{{ taskInfo.baseShopItem?.usageMethod }}</view>
        </view>
      </view>

      <!-- 产品图片 -->
      <view class="product-section">
        <image class="product-img" v-if="taskInfo.buyType === '01'" :src="BASE_URL + taskInfo.omsGoodsInfo?.detailImg" mode="aspectFill" />
        <image class="product-img" v-else-if="taskInfo.buyType === '02'" :src="BASE_URL + taskInfo.baseShopItem?.detailImg" mode="aspectFill" />
      </view>

      <!-- 图片上传区域 -->
      <view class="upload-section">
        <text class="section-title">上传图片/视频</text>
        <view class="upload-list">
          <view v-for="(img, index) in uploadedImages" :key="index" class="upload-item">
            <image :src="img" mode="aspectFill" class="uploaded-img" />
            <view class="delete-btn" @tap="deleteImage(index)">×</view>
          </view>
          <view v-if="uploadedImages.length < 3" class="upload-item add" @tap="chooseImage">
            <image class="add-icon" :src="images.icons.addImg" mode="aspectFit" />
          </view>
        </view>
      </view>

      <!-- 产品介绍 -->
      <view class="product-intro">
        <text class="section-title">产品介绍</text>
        <text class="intro-text">{{ taskInfo.baseShopItem?.itemDetail || taskInfo.omsGoodsInfo?.detail }}</text>
      </view>
    </view>

    <!-- 底部按钮 -->
    <view class="bottom-btn">
      <button class="btn" :disabled="isSubmitting" @tap="submitTask">
        {{ isSubmitting ? '提交中...' : '立即打卡' }}
      </button>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import { images, DEFAULT_IMAGE } from '@/config/images';
import { getTaskDetail, uploadFile, submitTaskRecord, type TaskItem } from '@/api/task';
import { type GoodsInfo } from '@/api/goods';
import { useUserStore } from '@/stores/user';
import { BASE_URL, IMG_URL } from '@/utils/request';

interface TaskInfo {
  taskId: string | number;
  taskContent: string;
  status: string;
  buyType: string;
  baseShopItem: GoodsInfo;
}

const taskInfo = ref<TaskInfo>({
  taskId: '',
  taskContent: '',
  status: '',
  buyType: '',
  baseShopItem: {},
});

const uploadedImages = ref<string[]>([]);
const uploadedUrls = ref<string[]>([]);
const isSubmitting = ref(false);

// 获取任务详情
const getTaskDetailInfo = async () => {
  try {
    const res = await getTaskDetail(taskInfo.value.taskId, taskInfo.value.buyType);
    console.log('任务详情响应：', res);
    if (res?.code === 200 && res.data) {
      // 更新任务信息
      taskInfo.value = {
        ...taskInfo.value,
        ...res.data,
      };
    }
  } catch (error) {
    console.error('获取任务详情失败：', error);
    uni.showToast({
      title: '获取任务详情失败',
      icon: 'none',
    });
  }
};

// 页面加载
onLoad((options) => {
  console.log('页面参数：', options);
  if (options) {
    // 从路由参数中获取任务信息
    taskInfo.value = {
      taskId: options.taskId,
      taskContent: decodeURIComponent(options.taskContent || ''),
      status: options.status || '',
      buyType: options.buyType || '',
    };

    // 获取任务详情
    getTaskDetailInfo();
  }
});

// 选择图片
const chooseImage = async () => {
  if (isSubmitting.value) return;

  try {
    const res = await uni.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
    });

    // 显示上传中状态
    isSubmitting.value = true;
    uni.showLoading({
      title: '上传中...',
    });

    // 上传图片到服务器
    try {
      // 先添加到显示图片数组，立即显示预览
      uploadedImages.value.push(res.tempFilePaths[0]);

      const uploadRes = await uploadFile(res.tempFilePaths[0]);
      console.log('上传结果：', uploadRes);

      if (uploadRes.code === 200 && uploadRes.fileName) {
        // 添加到已上传URL数组
        uploadedUrls.value.push(uploadRes.fileName);
      } else {
        // 如果上传失败，移除预览图片
        uploadedImages.value.pop();
        uni.showToast({
          title: uploadRes.msg || '图片上传失败',
          icon: 'none',
        });
      }
    } catch (error: any) {
      // 上传失败，移除预览图片
      uploadedImages.value.pop();
      console.error('上传失败：', error);
      uni.showToast({
        title: error.errMsg || '图片上传失败',
        icon: 'none',
      });
    }
  } catch (error: any) {
    console.error('选择图片失败：', error);
    uni.showToast({
      title: error.errMsg || '选择图片失败',
      icon: 'none',
    });
  } finally {
    isSubmitting.value = false;
    uni.hideLoading();
  }
};

// 删除图片
const deleteImage = (index: number) => {
  uploadedImages.value.splice(index, 1);
  uploadedUrls.value.splice(index, 1);
};

// 格式化日期
const formatDate = (date: Date): string => {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};

// 提交打卡
const submitTask = async () => {
  if (isSubmitting.value) return;
  if (uploadedUrls.value.length === 0) {
    uni.showToast({
      title: '请上传打卡图片',
      icon: 'none',
    });
    return;
  }

  try {
    isSubmitting.value = true;
    const userStore = useUserStore();
    const res = await submitTaskRecord({
      taskId: taskInfo.value.taskId,
      recordDate: formatDate(new Date()),
      points: 5,
      filesUrl: uploadedUrls.value.join(','),
      userId: userStore.userId,
    });

    if (res.code === 200) {
      uni.showToast({
        title: '打卡成功',
        icon: 'success',
      });
      // 延迟返回上一页
      setTimeout(() => {
        uni.navigateBack();
      }, 1500);
    } else {
      uni.showToast({
        title: res.msg || '打卡失败',
        icon: 'none',
      });
    }
  } catch (error) {
    console.error('打卡失败：', error);
    uni.showToast({
      title: '打卡失败',
      icon: 'none',
    });
  } finally {
    isSubmitting.value = false;
  }
};
</script>

<style lang="scss" scoped>
.info-section {
  margin: 20rpx 0;
  background: #fff;
  border-radius: 20rpx;

  .info-item {
    padding: 30rpx 0 0;
    white-space: inherit;
    display: flex;

    .label {
      font-size: 26rpx;
      height: 40rpx;
      color: #333;
      font-weight: 500;
      margin-bottom: 20rpx;
      display: block;
      background-color: #dadada;
      white-space: nowrap;
      width:120rpx;
      text-align: center;
    }

    .divider {
      height: 2rpx;
      background: #f5f5f5;
      margin: 20rpx 0;
    }

    .value {
      font-size: 26rpx;
      margin-left:20rpx;
      width:500rpx;
      color: #666;
      line-height: 1.6;
    }
  }
}
.detail-page {
  min-height: 100vh;
  background: #fff;
}

.reward-banner {
  width: 100%;
  height: 300rpx;
  position: relative;

  .banner-img {
    width: 100%;
    height: 350rpx;
  }

}

.task-content {
  padding: 30rpx;
  border-top-right-radius: 40rpx;
  border-top-left-radius: 40rpx;
  margin-top: -50rpx;
  z-index: 9;
  position: relative;
  width: 100%;
  box-sizing: border-box;
  background: #fff;
  .task-header {
    display: flex;
    align-items: center;
    gap: 20rpx;
    margin-bottom: 30rpx;

.title-section {
  padding: 20rpx 0 30rpx;
  
  .title {
    font-size: 36rpx;
    font-weight: 600;
    color: #333;
  }
}



    .usage-text {
      font-size: 28rpx;
      color: #333;
      line-height: 1.6;
    }
  }

  .upload-section {
    margin-bottom: 40rpx;

    .section-title {
      font-size: 28rpx;
      color: #333;
      margin-bottom: 20rpx;
      display: block;
    }

    .upload-list {
      display: flex;
      gap: 20rpx;
      flex-wrap: wrap;
    }

    .upload-item {
      width: 204rpx;
      height: 168rpx;
      border-radius: 12rpx;
      position: relative;
      overflow: hidden;

      &.add {
        display: flex;
        align-items: center;
        justify-content: center;

        .add-icon {
          width: 100%;
          height: 100%;
        }
      }

    .uploaded-img {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }

    .delete-btn {
      position: absolute;
      top: 10rpx;
      right: 10rpx;
      width: 40rpx;
      height: 40rpx;
      background: rgba(0, 0, 0, 0.5);
      border-radius: 50%;
      color: #fff;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 32rpx;
    }
  }
}

  .product-section {
    margin-bottom: 40rpx;

    .section-title {
      font-size: 28rpx;
      color: #333;
      margin-bottom: 20rpx;
      display: block;
    }

    .product-img {
      width: 100%;
      border-radius: 12rpx;
    }
  }

  .product-intro {
    .section-title {
      font-size: 28rpx;
      color: #333;
      margin-bottom: 20rpx;
      display: block;
    }

    .intro-text {
      font-size: 28rpx;
      color: #666;
      line-height: 1.6;
    }
  }
}
.bottom-btn {
  width: 100%;
  height: 70rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  padding-bottom: 80rpx;
  .btn {
    width: 400rpx;
    height: 100%;
    background: #ff9f40;
    border-radius: 40rpx;
    color: #fff;
    font-size: 28rpx;
    padding: 0;
    outline: none;
    border: none;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}
</style>
